/**
 * 
 */
package org.quotidian.jinger_project;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.cometd.Bayeux;
import org.cometd.Channel;
import org.cometd.Client;
import org.cometd.RemoveListener;
import org.mortbay.cometd.BayeuxService;
import org.mortbay.log.Log;

public class TransportService extends BayeuxService
{
	
	private String baseChannel = "/jinger";
	private String transportChannel = "/transport";
	
    /**
     * A map(channel, map(userName, clientId))
     */
    private final ConcurrentMap<String, Map<String, String>> _members = new ConcurrentHashMap<String, Map<String, String>>();
    
    public TransportService(Bayeux bayeux)
    {
        super(bayeux, "transport");
        subscribe(baseChannel+transportChannel, "transportSwitchyard");
    }
    
    public void transportSwitchyard(final Client joiner, final String channelName, Map<String, Object> data, final String messageId)
    {
        if (Boolean.TRUE.equals(data.get("join")))
        {
            Map<String, String> membersMap = _members.get(channelName);
            if (membersMap == null)
            {
                Map<String, String> newMembersMap = new ConcurrentHashMap<String, String>();
                membersMap = _members.putIfAbsent(channelName, newMembersMap);
                if (membersMap == null) membersMap = newMembersMap;
            }
            
            final Map<String, String> members = membersMap;
            final String userName = (String)data.get("user");
            members.put(userName, joiner.getId());
            joiner.addListener(new RemoveListener()
            {
                public void removed(String clientId, boolean timeout)
                {
                    members.values().remove(clientId);
                    Log.info("members: " + members);
                    // Broadcast the members to all existing members
                    Channel channel = getBayeux().getChannel(channelName, false);
                    if (channel != null) channel.publish(getClient(), members.keySet(), messageId);
                }
            });

            Log.info("Members: " + members);
            // Broadcast the members to all existing members
            getBayeux().getChannel(channelName, false).publish(getClient(), members.keySet(), messageId);
        } else {
        	Log.info("CHAT: " + data.get("user") + " : " + data.get("chat"));
        }
    }
}

